package com.mobile.collect.activitys;

import android.os.Bundle;
import android.os.Environment;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;

import com.mobile.collect.R;
import com.mobile.collect.beans.DeviceInfo;
import com.mobile.collect.beans.DevicePicInfo;
import com.mobile.collect.beans.DevicePointInfo;
import com.mobile.collect.db.EntityManager;
import com.mobile.collect.dialogs.v3.TipDialog;
import com.mobile.collect.present.BasePresent;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidmvp.base.BaseListActivity;
import cn.droidlover.xdroidmvp.base.BaseRecyclerAdapter;
import cn.droidlover.xdroidmvp.base.RecyclerViewHolder;
import cn.droidlover.xdroidmvp.kit.Kits;
import cn.droidlover.xdroidmvp.kit.NLog;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class ImportDataActivity extends BaseListActivity<File, BasePresent> {
    List<File> selectFiles = new ArrayList<>();
    @BindView(R.id.importBtn)
    Button importBtn;
    String dataDir;

    @Override
    public int getContentViewId() {
        return R.layout.activity_importdata;
    }

    @Override
    public void initView() {
        super.initView();
        titleTv.setText("导入");
        importBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (selectFiles.size() == 0) {
                    TipDialog.show(ImportDataActivity.this, "请选择要导入的备份日期文件", TipDialog.TYPE.ERROR);
                } else {
                    startImport(selectFiles.get(0).getName());
                }
            }
        });
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        dataDir = Environment.getExternalStorageDirectory() + "/" + getString(R.string.app_name) + "/备份/";
        super.initData(savedInstanceState);
    }

    @Override
    public BaseRecyclerAdapter<File> getAdapter() {
        return new BaseRecyclerAdapter<File>(this) {
            @Override
            public int getItemLayoutId(int viewType) {
                return R.layout.item_backupfile;
            }

            @Override
            public void bindData(RecyclerViewHolder holder, int position) {
                super.bindData(holder, position);
                File file = getItemByPosition(position);
                if (selectFiles.contains(file)) {
                    holder.setImageResDrawable(R.id.selectIv, R.mipmap.select1);
                } else {
                    holder.setImageResDrawable(R.id.selectIv, R.mipmap.select0);
                }
                holder.setText(R.id.dataTimeTv, file.getName());
            }
        };
    }

    @Override
    public void itemClick(int position) {
        File file = mBaseAdapter.getItemByPosition(position);
        if (selectFiles.contains(file)) {
            selectFiles.remove(file);
        } else {
            selectFiles.clear();
            selectFiles.add(file);
        }
        mBaseAdapter.notifyDataSetChanged();
    }

    @Override
    public void getDataFromServer() {
        File file = new File(dataDir);
        File[] files = file.listFiles();
        List<File> dataList = new ArrayList<>();
        for (File file1 : files) {
            if (file1.getName().endsWith("_backup")) {
                dataList.add(file1);
            }
        }
        onSuccess(dataList);
    }

    @Override
    public void getIntentData() {

    }

    @Override
    public BasePresent newP() {
        return new BasePresent();
    }

    private void startImport(String dateTime) {
        showLoadDialog();
        Observable.just(dateTime).subscribeOn(Schedulers.io()).map(new Func1<String, String>() {
            @Override
            public String call(String s) {
                EntityManager.getInstance().clearDb();
                try {
                    boolean result = importDatas(s);
                    if (result) {
                        return "导入成功";
                    } else {
                        return "导入失败";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    return e.getMessage();
                }
            }
        }).observeOn(AndroidSchedulers.mainThread()).subscribe(new Action1<String>() {
            @Override
            public void call(String message) {
                disLoadDialog();
                showToast(message);
                if (TextUtils.equals("导入成功", message)) {
                    finish();
                }
            }
        }, new Action1<Throwable>() {
            @Override
            public void call(Throwable throwable) {
                EntityManager.getInstance().clearDb();
                disLoadDialog();
                showToast("导入失败");
            }
        });
    }

    private boolean importDatas(String dateTime) throws Exception {
        String exportPath = dataDir
                + dateTime + "/data/";
        String backPicPath = dataDir
                + dateTime + "/pic/";
        StringBuilder jsonBuilder = Kits.File.readFile(exportPath + "devices.json", "utf-8");
        String json = jsonBuilder.toString();

        String devicesFile = exportPath + "devices.json";
        String unitsFile = exportPath + "units.json";
        String pointFile = exportPath + "point.json";
        if (!Kits.File.isFileExist(devicesFile)) {
            throw new Exception("缺少设备文件");
        }
        if (!Kits.File.isFileExist(unitsFile)) {
            throw new Exception("缺少测试单元文件");
        }
        if (!Kits.File.isFileExist(pointFile)) {
            throw new Exception("缺少密封点文件");
        }
        if (!new File(backPicPath).exists()) {
            throw new Exception("缺少图片文件");
        }


        List<DeviceInfo> list = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                DeviceInfo deviceInfo = new DeviceInfo();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                deviceInfo.set_ID(jsonObject.getLong("_ID"));
                deviceInfo.setDeviceName(getStringFromJson(jsonObject, "deviceName"));
                deviceInfo.setDeviceNo(getStringFromJson(jsonObject, "deviceNo"));
                deviceInfo.setDeviceDes(getStringFromJson(jsonObject, "deviceDes"));
                deviceInfo.setDeviceCompany(getStringFromJson(jsonObject, "deviceCompany"));
                deviceInfo.setCreateUser(getStringFromJson(jsonObject, "createUser"));
                deviceInfo.setCreateTime(getStringFromJson(jsonObject, "createTime"));
                deviceInfo.setEditTime(getStringFromJson(jsonObject, "editTime"));
                deviceInfo.setHadExport(jsonObject.getBoolean("hadExport"));
                deviceInfo.setIsMerge(jsonObject.getBoolean("isMerge"));
                list.add(deviceInfo);
            }
            EntityManager.getInstance().saveDeviceInfo(list);

        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        jsonBuilder = Kits.File.readFile(exportPath + "units.json", "utf-8");
        json = jsonBuilder.toString();
        List<DevicePicInfo> piclist = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                DevicePicInfo deviceInfo = new DevicePicInfo();
                JSONObject jsonObject = jsonArray.getJSONObject(i);
                deviceInfo.set_ID(jsonObject.getLong("_ID"));
                deviceInfo.setParentId(jsonObject.getLong("parentId"));// picInfo.getParentId());
                deviceInfo.setUnitName(getStringFromJson(jsonObject, "unitName"));// picInfo.getUnitName());
                deviceInfo.setDeviceName(getStringFromJson(jsonObject, "deviceName"));// picInfo.getDeviceName());
                deviceInfo.setDistance(getStringFromJson(jsonObject, "distance"));// picInfo.getDistance());
                deviceInfo.setReference(getStringFromJson(jsonObject, "reference"));// picInfo.getReference());
                deviceInfo.setLabel(getStringFromJson(jsonObject, "label"));// picInfo.getLabel());
                deviceInfo.setDirection(getStringFromJson(jsonObject, "direction"));// picInfo.getDirection());
                deviceInfo.setFloor(getStringFromJson(jsonObject, "floor"));// picInfo.getFloor());
                deviceInfo.setStatus(getStringFromJson(jsonObject, "status"));// picInfo.getStatus());

                String picPath = getStringFromJson(jsonObject, "picPath");
                int index = picPath.lastIndexOf("/");
                String picName = picPath.substring(index + 1);
                picPath = backPicPath + picName;
                NLog.d("picPath", "picPath =" + picPath);
                deviceInfo.setPicPath(picPath);// picInfo.getPicPath());
                deviceInfo.setPicNo(getStringFromJson(jsonObject, "picNo"));// picInfo.getPicNo());
                deviceInfo.setPicBitMapWidth(jsonObject.getInt("picBitMapWidth"));// picInfo.getPicBitMapWidth());
                deviceInfo.setPicBitmapHeight(jsonObject.getInt("picBitmapHeight"));// picInfo.getPicBitmapHeight());
                deviceInfo.setLableIsRepeat(jsonObject.getBoolean("lableIsRepeat"));// picInfo.getLableIsRepeat());
                deviceInfo.setIsCopy(jsonObject.getBoolean("isCopy"));// picInfo.isCopy());
                deviceInfo.setCreateTime(jsonObject.getLong("createTime"));// picInfo.getCreateTime());
                piclist.add(deviceInfo);
            }
            EntityManager.getInstance().saveDevicePicInfo(piclist);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }

        jsonBuilder = Kits.File.readFile(exportPath + "point.json", "utf-8");
        json = jsonBuilder.toString();

        List<DevicePointInfo> pointlist = new ArrayList<>();
        try {
            JSONArray jsonArray = new JSONArray(json);
            for (int i = 0; i < jsonArray.length(); i++) {
                DevicePointInfo deviceInfo = new DevicePointInfo();
                JSONObject jsonObject = jsonArray.getJSONObject(i);

                deviceInfo.set_ID(jsonObject.getLong("_ID"));//info.get_ID());
                deviceInfo.setParentId(jsonObject.getLong("parentId"));//info.getParentId());
                deviceInfo.setScaleX(Float.parseFloat(getStringFromJson(jsonObject, "scaleX")));//info.getScaleX());
                deviceInfo.setScaleY(Float.parseFloat(getStringFromJson(jsonObject, "scaleY")));//info.getScaleY());
                deviceInfo.setViewWidth(jsonObject.getInt("viewWidth"));//info.getViewWidth());
                deviceInfo.setViewHeight(jsonObject.getInt("viewHeight"));//info.getViewHeight());
                deviceInfo.setScreenX(jsonObject.getInt("screenX"));//info.getScreenX());
                deviceInfo.setScreenY(jsonObject.getInt("screenY"));//info.getScreenY());
                deviceInfo.setPointDircetion(getStringFromJson(jsonObject, "pointDircetion"));//info.getPointDircetion());
                deviceInfo.setDirection(jsonObject.getInt("direction"));//info.getDirection());
                deviceInfo.setBgType(jsonObject.getInt("bgType"));//info.getBgType());
                deviceInfo.setLineType(jsonObject.getInt("lineType"));//info.getLineType());
                deviceInfo.setLineType2(jsonObject.optString("lineType2"));//info.getLineType());
                deviceInfo.setDeviceName(getStringFromJson(jsonObject, "deviceName"));//info.getDeviceName());
                deviceInfo.setAddressNo(getStringFromJson(jsonObject, "addressNo"));//info.getAddressNo());
                deviceInfo.setExpendNo(getStringFromJson(jsonObject, "expendNo"));//info.getExpendNo());
                deviceInfo.setDiameter(getStringFromJson(jsonObject, "diameter"));//info.getDiameter());
                deviceInfo.setDistence(getStringFromJson(jsonObject, "distence"));//info.getDistence());
                deviceInfo.setHeight(getStringFromJson(jsonObject, "height"));//info.getHeight());
                deviceInfo.setType(getStringFromJson(jsonObject, "type"));//info.getType());
                deviceInfo.setTypeEn(getStringFromJson(jsonObject, "typeEn"));//info.getTypeEn());
                deviceInfo.setChildType(getStringFromJson(jsonObject, "childType"));//info.getChildType());
                deviceInfo.setChildTypeEn(getStringFromJson(jsonObject, "childTypeEn"));//info.getChildTypeEn());
                deviceInfo.setCheckHardType(getStringFromJson(jsonObject, "checkHardType"));//info.getCheckHardType());
                deviceInfo.setCheckHardReason(getStringFromJson(jsonObject, "checkHardReason"));//info.getCheckHardReason());
                deviceInfo.setDangerCheck(getStringFromJson(jsonObject, "dangerCheck"));//info.getDangerCheck());
                deviceInfo.setDangerCheckReaseon(getStringFromJson(jsonObject, "dangerCheckReaseon"));//info.getDangerCheckReaseon());
                deviceInfo.setHeatPreservation(getStringFromJson(jsonObject, "heatPreservation"));//info.getHeatPreservation());
                deviceInfo.setAdditionalDes(getStringFromJson(jsonObject, "additionalDes"));//info.getAdditionalDes());
                deviceInfo.setLabelName(getStringFromJson(jsonObject, "labelName"));//info.getLabelName());
                deviceInfo.setDeviceCount(jsonObject.getInt("deviceCount"));//info.getDeviceCount());
                deviceInfo.setStatus(getStringFromJson(jsonObject, "status"));//info.getStatus());
                deviceInfo.setIsNewPoint(jsonObject.getBoolean("isNewPoint"));//info.getIsNewPoint());
                deviceInfo.setCreateTime(jsonObject.optLong("createTime", 0l));//info.getIsNewPoint());
                pointlist.add(deviceInfo);
            }
            EntityManager.getInstance().savePointInfo(pointlist);
        } catch (JSONException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    private String getStringFromJson(JSONObject jsonObject, String labelName) {
        return jsonObject.optString(labelName, "");
    }
    @Override
    public boolean isNotWorkConnect() {
        return false;
    }
}
